package com.dangdang.dao;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Book;
import com.dangdang.domain.Category;
import com.dangdang.util.HbnUtil;

public class CategoryDao {
	
	/**
	 * @InsertCategory
	 * @param product
	 */
	public void InsertCategory(Category category) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.save(category);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		}
		s.close();
	}

	/**
	 * @Get category
	 * @return list
	 */
	public List<Category> getCategory() {
		Session s = HbnUtil.getSession();
		List<Category> categoryList = null;
		List<Category> categoryListOk = new ArrayList<Category>();
		Query query = s.createQuery("from Category");
		categoryList = query.list();
		for (Category category : categoryList) {
			if (category.getLevel()==2 ) {
				category.setName("&nbsp&nbsp;                "+category.getName());
				categoryListOk.add(category);
			} else {
				categoryListOk.add(category);
			}
		}
				
		return categoryListOk;
	}
	
//	public static void main(String[] args) {
//		Set<Category> cc = new HashSet<Category>();
//		Category category =  new Category();
//		category.setName("当代故事");
//		category.setLevel(2);
//		category.setParentLevel(1);
//		CategoryDao cd = new CategoryDao();
//		cd.InsertCategory(category);
//		
//		CategoryDao  cd = new CategoryDao();
//		List<Category> list  = cd.getCategory(); 
//			
//		for( int i=0; i<list.size(); i++){
//			Category category =  list.get(i);
//				if(category.getId() ==  5){
//					cc.add(category);
//				}
//			}
//		
//		Book book = new Book();
//		book.setAuthor("王培虎");
//		book.setName("Unix操作系统的使用");
//		book.setPrice(100.00);
//		book.setPublisher("机械工业出版社");
//		book.setPublishDate(null);
//		book.setCategory(cc);
//		BookDao bd = new BookDao();
//		bd.InsertBook(book);
//	}
	
	/**
	 * @update a Book
	 * @param Book
	 */
	public void updateCategory(Category category) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			
			
			s.getTransaction().commit();

		} catch (HibernateException e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		}
	}
	
}
